package cn.com.inossem.operation;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import cn.com.inossem.config.WSConfig;
import cn.com.inossem.db.DatabaseHelper;
import cn.com.inossem.model.UserInfo;
import cn.com.inossem.network.NetworkConnect;
import cn.com.inossem.requestmanager.WooRequestFactory;

import com.foxykeep.datadroid.exception.ConnectionException;
import com.foxykeep.datadroid.exception.CustomRequestException;
import com.foxykeep.datadroid.exception.DataException;
import com.foxykeep.datadroid.requestmanager.Request;
import com.foxykeep.datadroid.service.RequestService.Operation;
import com.google.gson.Gson;

public class FriendsDetaisOperation implements Operation {
	public static final String FRIENDS_OPERATION_PHONE = "friends_operation_phone";
	public Bundle bundle;

	Context content = null;

	@Override
	public Bundle execute(Context arg0, Request request)
			throws ConnectionException, DataException, CustomRequestException {
		content = arg0;

		String phone = request.getString(FRIENDS_OPERATION_PHONE);

		NetworkConnect connection = new NetworkConnect(WSConfig.LOCAL_URL
				+ "userInfo/findFriendByPhone");
		connection.setPostText("{\"phone\":\"" + phone + "\"}");
		System.out.println("{\"phone\":\"" + phone + "\"}");
		String body = connection.execute();

		System.out.println("FriendsDetaisOperation:" + body);
		bundle = new Bundle();
		try {
			JSONObject jsonObject = new JSONObject(body);
			int errorFlag = jsonObject.getInt("errorFlag");

			if (errorFlag == WSConfig.RESULT_SUCESS) {

				Gson datagson = new Gson();

				// LoginresultData loginresultdata = datagson.fromJson(body,
				// LoginresultData.class);

				String friend = jsonObject.get("friend").toString();
				UserInfo userinfo = datagson.fromJson(friend, UserInfo.class);

				// String preferencesStr = jsonObject.get("preferences")
				// .toString();
				// RetrieveInfoBean preferences = datagson.fromJson(
				// preferencesStr, RetrieveInfoBean.class);
				// bundle.putParcelable(WooRequestFactory.PREFERENCES_SETING_DATA,
				// preferences);
				// 返回登陆的返回值
				bundle.putParcelable(WooRequestFactory.RESPONSE_LOGIN_DATA,
						userinfo);

				// 设置登陆结果

			}
			bundle.putInt(WooRequestFactory.BUNDLE_EXTRA_LOGIN, errorFlag);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return bundle;
	}

	public void charu(String tabname, ContentValues contentValues,
			String whereClause) {
		DatabaseHelper dh = new DatabaseHelper(content);
		SQLiteDatabase db = dh.getWritableDatabase();

		db.update(tabname, contentValues, whereClause, null);

		db.close();
		dh.close();
	}
}
